package com.stock.demo.framework.ui.activity;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;

import com.stock.demo.framework.ui.INetAccess;
import com.stock.demo.framework.ui.NetCompleteBean;
import com.stock.demo.framework.ui.NetErrorBean;
import com.stock.demo.framework.ui.NetPageState;
import com.stock.demo.framework.ui.view.BaseNetPage;

import io.reactivex.ObservableEmitter;

/**
 * Created by XuZhaoyu on 2017/5/15.
 */

public abstract class BaseNetActivity extends BaseActivity implements INetAccess {

    private BaseNetPage mNetPage;
    private ObservableEmitter mEmitter;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initNetPage();
        setContentView(mNetPage);
        initView();
        initData();
    }

    private void initNetPage() {
        if (mNetPage == null) {
            mNetPage = new BaseNetPage(this) {

                @Override
                public View createSuccessView() {
                    return onCreateSuccessView();
                }

                @Override
                public void onReloadClick(View v) {
                    mNetPage.changePageState();
                    onReload(v);
                }

                @Override
                public void getEmitter(ObservableEmitter emitter) {
                    mEmitter = emitter;
                }
            };
        }

        mNetPage.setOnNetStateChangeListener(new BaseNetPage.OnNetStateChangeListener() {
            @Override
            public void onNetStateChange(NetPageState state) {
                // TODO: 2017/5/22 根据需求增加页面切换的逻辑
            }
        });

    }

    /**
     * 该方法在onCreate（）中执行，用于绑定控件
     */
    public abstract void initView();

    /**
     * 该方法在onCreate（）中执行，用于对数据进行初始化
     */
    public abstract void initData();

    @Override
    public BaseNetActivity onNetNext(Object netBean) {
        if (mEmitter != null) {
            mEmitter.onNext(netBean);
        }
        return this;
    }

    @Override
    public void setNetComplete() {
        if (mEmitter != null) {
            mEmitter.onNext(new NetCompleteBean());
        }
    }

    @Override
    public void setNetError() {
        if (mEmitter != null) {
            mEmitter.onNext(new NetErrorBean());
            mEmitter.onNext(new NetCompleteBean());
        }
    }

    /**
     * 该方法在OnCreate（）中执行，用于构建加载成功后的页面
     *
     * @return 返回加载成功后的页面
     */
    public abstract View onCreateSuccessView();

    /**
     * 重新载入按钮的点击事件
     *
     * @param v 重新载入按钮(TextView)自身
     */
    public abstract void onReload(View v);
}
